from django.contrib import admin
from django.db.models import Q
from django.contrib import messages
from django.utils.safestring import mark_safe

# from interview.dingtalk import send
from .task import send_dingtalk_message
from interview.models import Candidate
from django.http import HttpResponse
from interview.candidate_fieldset import *

import logging
import csv
from datetime import datetime

from jobs.models import Resume

logger = logging.getLogger(__name__)

exportable_fields = (
    'username', 'city', 'phone', 'bachelor_school', 'master_school', 'degree', 'first_result', 'first_interviewer_user',
    'second_result', 'second_interviewer_user', 'hr_result', 'hr_score', 'hr_remark', 'hr_interviewer_user')


def notify_interviewer(modeladmin, request, queryset):
    candidates = ""
    interviewers = ""
    for obj in queryset:
        candidates = obj.username + ";" + candidates
        interviewers = obj.first_interviewer_user.username + ';' + interviewers
    send_dingtalk_message.delay(f'候选人 {candidates} 进入面试环节, 亲爱的面试官,请准备好面试: {interviewers}')
    messages.add_message(request, messages.INFO, f'候选人 {candidates} 进入面试环节')


notify_interviewer.short_description = u'通知一面面试官'


def export_model_as_csv(modeladmin, request, queryset):
    response = HttpResponse(content_type='text/csv')
    field_list = exportable_fields
    response['Content-Disposition'] = 'attachment; filename=recruitment-candidates-list-%s.csv' % (
        datetime.now().strftime('%Y-%m-%d-%H-%M-%S'))

    writer = csv.writer(response)
    writer.writerow(
        [queryset.model._meta.get_field(f).verbose_name.title() for f in field_list]
    )

    for obj in queryset:
        csv_line_values = []
        for field in field_list:
            field_object = queryset.model._meta.get_field(field)
            field_value = field_object.value_from_object(obj)
            csv_line_values.append(field_value)
        writer.writerow(csv_line_values)
    logger.error(f'{request.user} exported {len(queryset)} candidate records')
    return response


export_model_as_csv.short_description = u'导出为csv文件'
export_model_as_csv.allowed_permissions = ('export',)  # 设置权限为export, export是model的meta属性里定义的


class CandidateAdmin(admin.ModelAdmin):
    exclude = ('creator', 'created_date', 'modified_date')

    actions = [export_model_as_csv, notify_interviewer, ]

    list_per_page = 5

    # 查看用户是否有导出权限
    def has_export_permission(self, request):
        opts = self.opts
        print(opts)
        print(opts.app_label)
        return request.user.has_perm(f'{opts.app_label}.export')

    list_display = (
        'username', 'city', 'bachelor_school', 'first_score', 'first_result', 'first_interviewer_user',
        'second_result', 'second_interviewer_user', 'hr_score', 'hr_result', 'hr_interviewer_user', 'last_editor',
        'get_resume',
    )

    # 查询字段
    search_fields = ('username', 'phone', 'email', 'bachelor_school',)
    # 过滤字段
    list_filter = (
        'city', 'first_result', 'second_result', 'hr_result', 'first_interviewer_user', 'second_interviewer_user',
        'hr_interviewer_user')

    ordering = ('hr_result', 'second_result', 'first_result',)

    def get_resume(self, obj):
        if not obj.phone:
            return ''
        resume = Resume.objects.filter(phone=obj.phone)
        if resume and len(resume) > 0:
            return mark_safe(f'<a href="/resume/{resume[0].id}/" target="_blank">查看简历</a>')

    get_resume.short_description = '查看简历'
    get_resume.allow_tags = True

    default_list_editable = ('first_interviewer_user', 'second_interviewer_user',)

    # readonly_fields = ('first_interviewer_user', 'second_interviewer_user', )

    def get_list_editable(self, request):
        # model admin并未对list_editable实现动态获取的方法
        group_names = self.get_group_names(request.user)

        if request.user.is_superuser or 'hr' in group_names:
            return self.default_list_editable
        return ()

    def get_changelist_instance(self, request):
        self.list_editable = self.get_list_editable(request)
        return super().get_changelist_instance(request)

    def get_readonly_fields(self, request, obj=None):
        group_names = self.get_group_names(request.user)

        if 'interviewer' in group_names:
            logger.info("interviewer is in user's group for %s " % request.user.username)
            return ('first_interviewer_user', 'second_interviewer_user',)
        return ()

    def get_fieldsets(self, request, obj=None):
        group_names = self.get_group_names(request.user)

        if 'interviewer' in group_names and obj.first_interviewer_user == request.user:
            return default_field_sets_first
        if 'interviewer' in group_names and obj.second_interviewer_user == request.user:
            return default_field_sets_second
        return default_fieldsets

    def get_group_names(self, user):
        group_names = []
        for g in user.groups.all():
            group_names.append(g.name)
        return group_names

    def get_queryset(self, request):
        qs = super(CandidateAdmin, self).get_queryset(request)

        group_names = self.get_group_names(request.user)

        if request.user.is_superuser or 'hr' in group_names:
            return qs
        return Candidate.objects.filter(
            Q(first_interviewer_user=request.user) | Q(second_interviewer_user=request.user)
        )


admin.site.register(Candidate, CandidateAdmin)
